<?
App::uses('Controller','Controller');
App::import('Vendor','Facebook',array('file'=>'facebook-sdk-3/src/facebook.php'));
class FacebookCpsController extends AppController{
	public $name = 'FacebookCps';
	public $uses = array();
	public function index(){
		$this->layout = false;

	}
	public function login(){
		$appId = Configure::read('FB_APP_ID');
		$app_secret = Configure::read('FB_APP_SECRET');
		$facebook = new Facebook(array(
			'appId'=>$appId,
			'secret'=>$app_secret));
		$loginUrl = $facebook->getLoginUrl(
			array(
				'scope'=>'email,read_stream, publish_stream, user_birthday, user_location, user_work_history, user_hometown, user_photos',
				'redirect_url'=>Configure::read('SITE_URL').facebook_cps/facebook_connect,
				'display'=>'popup'));
		$this->redirect($loginUrl);
	}
	function facebook_connect(){
		$appId = Configure::read('FB_APP_ID');
		$app_secret = Configure::read('FB_APP_SECRET');
		$facebook = new Facebook(array(
			'appId'=>$appId,
			'secret'=>$app_secret));
		$user = $facebook->getUser();
		if($user){
			try{
				$user_profile = $facebook->api('/me');
				$params = array('next'=>Configure::read('SITE_URL').facebook_cps/facebook_logout);
				$logout = $facebook->getLoutoutUrl($params);
				$this->Session->write('User',$user_profile);
				$this->Session->write('logout',$logout);
			}catch(FacebookApiException $ex){
				error_log($ex);
				$user = NULL;
			}
		}else{
			$this->Session->setFlash('Sorry.Please try again','default',array('class'=>'msg_req'));
			$this->redirect(array('action'=>'index'));
		}
	}
	function facebook_logout(){
		$this->Session->delete('User');
		$this->Session->delete('logout');
		$this->redirect(array('action'=>'index'));
	}
}
?>